<template>
  <div>
    <Header>
      <div slot="title" class="header-title">注册</div>
      <div slot="left" class="header-left">
        <img src="@/assets/index/back.png" alt />
      </div>
    </Header>
    <div class="organizaRegistr">
      <div class="logo">
        <div>
          <img src="./img/logo.png" />
        </div>
      </div>
      <div class="account-form">
        <van-form :show-error='false' validate-first validate-trigger='onSubmit' @submit="onSubmit" ref="form">
          <van-field
            v-model="account"
            @blur="blur('account',account)"
            @input="change('account',account)"
            name="account"
            clearable
            placeholder="请输入用户名"
            :rules="[
              {
                required: true,
                validator: validateAccount,
                message: (value)=>{
                  if(!value){
                    return '请输入用户名'
                  }
                  if(value.length<4 ||value.length>20 ){
                    return '长度4-20个字符之间'
                  }
                  if(!this.validateAccount(value)){
                    return '格式错误，仅支持字母、数字、“-”、“_”'
                  }
                }
              },
            ]"
          >
            <template slot="left-icon" name="left-icon">
              <img class="phone-ico" src="./img/user-ico.png" />
            </template>
          </van-field>
          <van-field
            v-model="password"
             @blur="blur('password',password)"
            @input="change('password',password)"
            :type="passwordType"
            name="password"
            clearable
            placeholder="请设置密码"
            :rules="[
              {
                required: true,
                validator: validatePass,
               message: (value)=>{
                  if(!value){
                    return '请输入密码'
                  }
                  if(value.length<6 || value.length>20){
                    return '长度6-20个字符之间'
                  }
                  if(this._str(value.toString(), value.toString()[0]) == value.toString().length){
                    return '不能使用同一字符'
                  }
                  
                  if(!this.validatePass(value)){
                    return '非法字符，请使用字母、数字的组合，6-20个字符'
                  }
                },
              },
            ]"
          >
            <template slot="left-icon" name="left-icon">
              <img class="password-ico" src="./img/password-ico.png" />
            </template>
            <template
              class="password-field"
              slot="right-icon"
              name="right-icon"
            >
              <img
                class="password-right"
                :src="
                  passwordType === 'password'
                    ? require('./img/ico-guanbi.png')
                    : require('./img/ico-zhangkai.png')
                "
                @click="switchPasswordType"
              />
            </template>
          </van-field>
          <van-field
            v-model="code"
             @blur="blur('code',code)"
            @input="change('code',code)"
            name="code"
            clearable
            placeholder="您的机构注册码"
            :rules="[{ required: true, message: '请填写机构注册码' }]"
          >
            <template slot="left-icon" name="left-icon">
              <img class="phone-ico" src="./img/ico-jigou.png" />
            </template>
          </van-field>
        </van-form>
        <div style="margin: 25px">
          <van-button
            style="color:#fff;"
            class="organizaRegistrButton"
            round
            block
            type="default"
            native-type="submit"
            @click="()=>{
              this.$refs['form'].submit();
            }"
            >立即注册</van-button
          >
        </div>
        <p
          class="kuaijie"
          @click="
            () => {
              this.$router.push({ path: '/login/sign' });
            }
          "
        >
          已有账号？快去登录吧
        </p>
        <p class="tiaoyue">
          注册表示您同意<span
            @click="
              () => {
                this.$router.push({ path: '/login/agree' });
              }
            "
            >《用户服务协议》</span
          >和<span
            @click="
              () => {
                this.$router.push({ path: '/login/agreeYinsi' });
              }
            "
            >《用户隐私政策》</span
          >
        </p>
        <br/><br/><br/><br/>
      </div>
    </div>
    <!-- 滑块验证码 -->
        <Verify
          @success="register"
          :captchaType="'blockPuzzle'"
          :phone="phoneNum"
          :imgSize="{width:'400px',height:'200px'}"
          ref="register"
        ></Verify>
  </div>
</template>

<script>
import Header from "@/components/header.vue";
import { Form, Field, Button, Divider } from "vant";
import {
  memberRegisterAPI,
  asyncValidateCodeAPI,
  asyncValidateAccountAPI,
} from "./api/login";
import {
  warningMessage,
  successMessage,
  errorMessage,
  linkName,
  linkOpen,
} from "./utils/function";
import { CODE_TYPE, BUSINESS_TYPE, RESET_TIME } from "./utils/constant";
import Verify from './component/verifition/Verify'
import userInfo from "./index"
import md5 from "js-md5";
export default {
  data() {
    return {
      passwordType: "password",
      account: "",
      password: "",
      code: "",
      loginLoading: false,
      phoneNum:undefined
    };
  },
  components: {
    Header,
    Verify,
    [Form.name]: Form,
    [Field.name]: Field,
    [Button.name]: Button,
    [Divider.name]: Divider,
  },
  methods: {
   blur(type,v){
      let me = this;
      if(v){
        let form = 'form';
        switch (type) {
          case 'account':
            this.$refs[form].validate('account');
            break;
          case 'password':
            this.$refs[form].validate('password');
            break;
          case 'code':
            this.$refs[form].validate('code');
            break;
          default:
            break;
        }
      }
    },
    change(type,v){
      if(v){
         let form = 'form';
         this.$refs[form].resetValidation();
        let me = this;
        switch (type) {
          case 'account':
            this.$refs[form].validate('account');
            break;
          case 'password':
            this.$refs[form].validate('password');
            break;
          case 'code':
            this.$refs[form].validate('code');
            break;
          default:
            break;
        }
      }
    },
    _str(value, n){
        var tmp = 0;
        for(var i = 0; i < value.length; i++){
            if(value.charAt(i) == n){    //charAt()方法可返回指定位置的字符
              tmp++;
            }
        }
        return tmp;    
    }, 
    async onSubmit() {
      if(this.loginLoading) return
      let res = await this._validate('code')
      let result = await this._validate('account')
      this.$refs.register.show()
    },
    switchPasswordType() {
      this.passwordType == "password"
        ? (this.passwordType = "text")
        : (this.passwordType = "password");
    },
    _validate(type){
      let typeObj = {
        'code':{
          API:asyncValidateCodeAPI
        },
        'account':{
          API:asyncValidateAccountAPI
        }
      }
      let data = {}
      data[type] = this[type]
      let API = typeObj[type].API(data)
      return new Promise((resolve,reject)=>{
        API.then(res=>{
          if(res.data.code === 0){
            let data = res.data.data 
            resolve(true)
          }else{
            reject(res.data.msg)
            warningMessage(res.data.msg)
          }
        },error=>{
          warningMessage(res.data.msg)
          reject(res.data.msg)
        })
      })

    },
    register(val){
      this.loginLoading = true
      let me = this;
      let { value, uuid } = val
      let data = {
        account:me.account,
        code:me.code,
      };
      data.password = md5(me.password)
      data.captchaForm = {
        phone:me.account,
        businessType:BUSINESS_TYPE['reg'],
        type:CODE_TYPE['blockPuzzle'],
        uuid,
        value
      }
      memberRegisterAPI(data).then(res=>{
        if(res.data.code === 0){
          let data = res.data.data
          localStorage.setItem('y-token',data.loginVo.token)
          localStorage.setItem('level',data.member.level)
          userInfo.sign(data)
          this.loginJump()
        }else{
          this.loginLoading = false
          warningMessage(res.data.msg)
        }
      },error=>{
        this.loginLoading = false
      })
    },
    loginJump(){
       let me = this;
        successMessage('注册成功',()=>{
          this.loginLoading = false
          me.$router.push({path:'/'})
      })
    },
    validateAccount(value) {
      let reg = /^[a-zA-Z0-9_-]{4,20}$/;
      return reg.test(value);
    },
    validatePass(value) {
      let reg = /^(?=.*\d)[A-Za-z\d]{6,20}$/;
      let flag = reg.test(value);
      if(flag){
        flag = !(this._str(value, value[0]) == value.length)
      }
      return flag
    },
  },
};
</script>

<style lang="scss">
@import "./css/index.scss";
.organizaRegistr {
  width: 100%;
  margin-top: 41px;
  .logo {
    width: 100%;
    height: 200px;
    display: flex;
    justify-content: center;
    align-items: center;
    img {
      width: 125px;
      height: 125px;
    }
  }
}
.organizaRegistrButton {
  background-image: url("./img/denglu-but.png");
  background-repeat: no-repeat;
  background-position: center;
  background-size: 100% 100%;
  color: #ffffff !important;
}
</style>